package com.oceanread.cn.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oceanread.cn.config.MyConfig;
import com.oceanread.cn.config.Result;
import com.oceanread.cn.entity.Pipeline;
import com.oceanread.cn.entity.Profile;
import com.oceanread.cn.entity.Query;
import com.oceanread.cn.service.IProfileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

import static com.oceanread.cn.controller.Drillhole1Controller.uploadFile;

@RestController
@RequestMapping("/Profile")
@CrossOrigin()
@Api(value = "", tags = {"2.2-浅剖信息"})
public class ProfileController {
    @Autowired
    private IProfileService iProfileService;

    @GetMapping("/getall")
    public List<Profile> getAll() {
        return iProfileService.getall();
    }

    @GetMapping("/findall")
    public JSONObject findall(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                              @RequestParam(name = "size", required = true, defaultValue = "10") int size) {
        JSONObject object = new JSONObject();
        object.put("data", iProfileService.findall(page, size));
        object.put("total", iProfileService.getnum());
        return object;
    }

    @GetMapping("/query")
    public JSONObject query(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                            @RequestParam(name = "size", required = true, defaultValue = "10") int size,
                            @RequestParam(name = "key") String key,
                            @RequestParam(name = "value") String value) {
        JSONObject object = new JSONObject();
        object.put("data", iProfileService.query(page, size, key, value));
        object.put("total", iProfileService.getnumquery(key, value));
        return object;
    }
    @ApiOperation(value = "更新浅剖线ID")
    @PostMapping("/updateIDline")
    public Integer updateIDline (@RequestBody Profile profile) {
        List<Profile> profile0=iProfileService.queryNopage("SYSID",String.valueOf(profile.getSYSID()));
        List<Profile> profileList =iProfileService.queryNopage2("PrjCode",profile0.get(0).getPrjCode(),"IDLine",profile0.get(0).getIDline());
        for (Profile profile1:profileList){
            profile1.setIDline(profile.getIDline());
            iProfileService.update(profile1);
        }
        return 1;
    }

    @ApiOperation(value = "更新浅剖节点")
    @PostMapping("/update")
    public Integer update(@RequestBody Profile profile) {
        System.out.println(profile);
//        重新写传值
        return iProfileService.update(profile);
    }

    @PostMapping("/insert")
    public Integer insert(@RequestBody Profile profile) {
        return iProfileService.insert(profile.getPrjCode(), profile.getCode(), profile.getName(),
                profile.getIDline(), profile.getOrder(), profile.getLat(), profile.getLon());
    }

    @ApiOperation(value = "删除浅剖节点")
    @GetMapping("/deleteNote")
    public Integer delete(@RequestParam(name = "SYSID") int SYSID) {
        System.out.println("删除Profile浅剖节点："+SYSID);
        return iProfileService.delete(SYSID);
    }
    @ApiOperation(value = "删除浅剖线ID")
    @GetMapping("/deleteIDline")
    public Integer deleteIDline (@RequestParam(name = "SYSID") int SYSID) {
        List<Profile> profile0=iProfileService.queryNopage("SYSID",String.valueOf(SYSID));
        List<Profile> profileList =iProfileService.queryNopage2("PrjCode",profile0.get(0).getPrjCode(),"IDLine",profile0.get(0).getIDline());
        System.out.println("批量删除Profile浅剖节点 IDLine："+profile0.get(0).getIDline());
        for (Profile profile1:profileList){
            System.out.println("批量删除Profile浅剖节点："+profile1.getSYSID());
            iProfileService.delete(profile1.getSYSID());
        }
        return 1;
    }

    @RequestMapping(value = "/uploadPhoto/{prjCode}", method = RequestMethod.GET)
    @ResponseBody
    public Result uploadPhoto(@PathVariable("prjCode") String prjCode, @RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        //设置文件上传路径
        String filePath = MyConfig.getFilepath() + "image/Profile/" + prjCode + "/";
        System.out.println(filePath + fileName);
        try {
            uploadFile(file.getBytes(), filePath, fileName);
            return Result.success();
        } catch (Exception e) {
            return Result.error();
        }
    }

    @RequestMapping(value = "/getPhoto/{PrjCode}/{imgname}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getPhoto(@PathVariable("PrjCode") String PrjCode, @PathVariable("imgname") String imgname) {
        try {
            System.out.println(imgname);
            File file = new File(MyConfig.getFilepath() + "image/Profile/" + PrjCode + "/" + imgname);
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    @RequestMapping(value = "/uploadGeojson", method = RequestMethod.GET)
    @ResponseBody
    public Result uploadGeojson(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String filetype = fileName.substring(fileName.lastIndexOf("."));
        if (filetype.equals(".json"))//处理xls文件
        {
            try {
                String rootPath = MyConfig.getFilepath() + "json/Profile/";
                String storagePath = rootPath + file.getOriginalFilename();
                /*保存文件*/
                Streams.copy(file.getInputStream(), new FileOutputStream(storagePath), true);
                System.out.println(storagePath);
                return Result.success();
            } catch (IOException e) {
                return Result.error(e.getMessage());
            }
        }
        return Result.error();
    }

    @RequestMapping(value = "/getGeojsonfile/{JsonName}", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public byte[] getGeojsonfile(@PathVariable("JsonName") String JsonName) {
        try {
            System.out.println(JsonName);
            File file = new File(MyConfig.getFilepath() + "json/Profile/" + JsonName);
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    @ApiOperation(value = "前端可视化 获得浅剖Geojson")
    @RequestMapping(value = "/getGeojson/{prjCode}", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getGeojson(@PathVariable(value = "prjCode") String prjCode) {
        try {
            JSONArray features = new JSONArray();
            List<Profile> profiles = iProfileService.getLine(prjCode);
            for (Profile profile : profiles) {
                JSONObject feature = new JSONObject();
                feature.put("type", "Feature");

                JSONObject properties = new JSONObject();
                properties.put("PrjCode", profile.getPrjCode());
                properties.put("Name", profile.getName());
                properties.put("IDLine", profile.getIDline());
                feature.put("properties", properties);

                System.out.println(profile.getIDline());
                List<Profile> points = iProfileService.getPoint(prjCode, profile.getIDline());

                JSONObject geometry = new JSONObject();
                geometry.put("type", "LineString");
                ArrayList<float[]> coordinates = new ArrayList<float[]>();
                for (Profile point : points) {
                    float[] lonlat = new float[2];
                    lonlat[0] = Float.parseFloat(point.getLon());
                    lonlat[1] = Float.parseFloat(point.getLat());
                    coordinates.add(lonlat);
                }
                geometry.put("coordinates", coordinates);
                feature.put("geometry", geometry);
                features.add(feature);
            }

            JSONObject geojson = new JSONObject();
            geojson.put("type", "FeatureCollection");
            geojson.put("features", features);
            return geojson;
        } catch (Exception e) {
            JSONObject object = new JSONObject();
            object.put("error", e.getMessage());
            return object;
        }
    }

    @ApiOperation(value = "后台获取浅剖信息")
    @RequestMapping(value = "/getinfo/{prjCode}", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getinfo(@PathVariable("prjCode") String prjCode,
                              @RequestParam(name = "page", required = true, defaultValue = "1") int page,
                              @RequestParam(name = "size", required = true, defaultValue = "10") int size) {
        try {
            JSONObject result = new JSONObject();
            JSONArray infos = new JSONArray();
            List<Profile> profiles = iProfileService.getLine_Page(prjCode, page, size);
            for (Profile profile : profiles) {
                JSONObject info = new JSONObject();
                info.put("SYSID", profile.getSYSID());
                info.put("PrjCode", profile.getPrjCode());
                info.put("Name", profile.getName());
                info.put("IDLine", profile.getIDline());
                infos.add(info);
            }
            Integer total = iProfileService.getLine_Num(prjCode);
            result.put("data", infos);
            result.put("total", total);
            return result;
        } catch (Exception e) {
            JSONObject object = new JSONObject();
            object.put("error", e.getMessage());
            return object;
        }
    }

    @ApiOperation(value = "后台获取浅剖节点")
    @RequestMapping(value = "/getnotes/{prjCode}/{IDLine}", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getnotes(@PathVariable("prjCode") String prjCode, @PathVariable("IDLine") String IDLine,
                              @RequestParam(name = "page", required = true, defaultValue = "1") int page,
                              @RequestParam(name = "size", required = true, defaultValue = "10") int size) {
        try {
            JSONObject result=new JSONObject();
            JSONArray notes = new JSONArray();
//            List<Profile> profiles = iProfileService.getPoint(prjCode, IDLine);
            List<Profile> profiles = iProfileService.getPoint_Page(prjCode, IDLine,page,size);
            for (Profile profile : profiles) {
                JSONObject info = new JSONObject();
                info.put("SYSID", profile.getSYSID());
                info.put("PrjCode", profile.getPrjCode());
                info.put("Name", profile.getName());
                info.put("IDLINE", profile.getIDline());
                info.put("Lon", profile.getLon());
                info.put("Lat", profile.getLat());
                info.put("Order", profile.getOrder());
                notes.add(info);
            }
            Integer total=iProfileService.getPoint_Num(prjCode,IDLine);
            result.put("data",notes);
            result.put("total",total);
            return result;
        } catch (Exception e) {
            JSONObject error = new JSONObject();
            error.put("error", e.getMessage());
            return error;
        }
    }

    @ApiOperation(value = "Profile统一插入")
    @RequestMapping(value = "/ProfileInsert", method = RequestMethod.POST)
    public void inserttest(HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader reader = request.getReader();
            if (reader != null) {
                String redaline = reader.readLine();
                JSONObject readobject = JSONObject.parseObject(redaline);
                JSONObject data = readobject.getJSONObject("data");
                System.out.println(data);
                String PrjCode = data.getString("PrjCode");
                String Name = data.getString("Name");

                String IDLine = data.getString("IDLine");
                JSONArray information = data.getJSONArray("Information");
                ArrayList<Profile> profileArrayList = new ArrayList<Profile>();
               if (information.size() > 0) {
                    for (int i = 0; i < information.size(); i++) {
                        Profile profile = new Profile();
                        profile.setPrjCode(PrjCode);
                        profile.setName(Name);
                        profile.setIDline(IDLine);
                        profile.setOrder(information.getJSONObject(i).getString("Order"));
                        profile.setLon(information.getJSONObject(i).getString("Lon"));
                        profile.setLat(information.getJSONObject(i).getString("Lat"));
                        profileArrayList.add(profile);
                    }
                }
                for (Profile profile:profileArrayList){
                     iProfileService.insert(profile.getPrjCode(), profile.getCode(), profile.getName(),
                            profile.getIDline(), profile.getOrder(), profile.getLat(), profile.getLon());
                }

            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        System.out.println();

    }
}
